package com.future.doc.excel;

import com.future.doc.util.Resources;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;

/**
 * 遍历Excel表格中的数据
 *
 * @author shiyong
 * 2021/8/16 7:28
 */
public class TraversalExcelData {

    public static void main(String[] args) {
        InputStream is = null;
        XSSFWorkbook wb = null;

        try {
            is = Resources.getResourceAsStream("/excel/TraversalExcelData.xlsx");
            wb = new XSSFWorkbook(is);
            XSSFSheet sheet = wb.getSheetAt(0);

            for (Row row : sheet) {
                for (Cell cell : row) {
                    StringBuilder content = new StringBuilder("第").append(row.getRowNum() + 1)
                            .append("行，第").append(cell.getColumnIndex() + 1).append("列，数据：");
                    if (cell.getCellType().equals(CellType.STRING)) {
                        content.append(cell.getStringCellValue());
                    } else if (cell.getCellType().equals(CellType.NUMERIC)) {
                        content.append(cell.getNumericCellValue());
                    }
                    System.out.println(content);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (wb != null) {
                try {
                    wb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
